package util;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;

/**
 * Created by MrWang on 2016/10/18.
 */
public class ShowPop {
    public static final int defaultBotom = -100;

    /**
     * @param attachOnView  PopupWindow显示在这个View的下方
     * @param popView       显示在PopupWindow上的View
     * @param popShowHeight 在PopupWindow上的View的高度，可以传默认值defaultBotom
     * @param popShowWidth  在PopupWindow上的View的宽度，一般是传attachOnView的getWidth()
     * @return PopupWindow
     */
    public static PopupWindow show(View attachOnView, int prox, View popView, int height, final int popShowWidth, final int popShowHeight) {
        if (popView != null && popView.getParent() != null) {
            ((ViewGroup) popView.getParent()).removeAllViews();
        }

        PopupWindow popupWindow = null;
        //Rect frame = new Rect();
        // activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);

        int location[] = new int[2];
        int x, y;
        int popHeight = 0, popWidth = 0;

        attachOnView.getLocationOnScreen(location);
        x = location[0];
        y = location[1];

        int h = attachOnView.getHeight();
        x = x - popShowWidth / 2;
        //  int screenHeight = DeviceInfoManager.getInstance().getScreenHeight();
        int screenHeight = height;
        if (popShowHeight == defaultBotom) {
            popHeight = screenHeight / 6;
            popHeight = Math.abs(screenHeight - (h + y)) - popHeight;
        } else if (popHeight == ViewGroup.LayoutParams.WRAP_CONTENT) {
            popHeight = ViewGroup.LayoutParams.WRAP_CONTENT;
        } else {
            popHeight = popShowHeight;
        }

        if (popShowWidth == ViewGroup.LayoutParams.WRAP_CONTENT) {
            popWidth = attachOnView.getWidth();
        } else {
            popWidth = popShowWidth;
        }

        popupWindow = new PopupWindow(popView, popWidth, popHeight, true);

        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#00000000")));
        //  popupWindow.setFocusable(true);
        popupWindow.showAtLocation(attachOnView, Gravity.NO_GRAVITY, x , y);
        popupWindow.update();
        return popupWindow;
    }

}